import { Color, Mesh, MeshBasicMaterial, OrthographicCamera, PlaneBufferGeometry, Scene, ShaderMaterial, Vector3, WebGLRenderer } from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new OrthographicCamera(
  -1, // left
  1, // right
  1, // top
  -1, // bottom
  -1, // near
  1,  // far
)
const plane = new PlaneBufferGeometry(2, 3)

// 片元着色器
const fragmentShader = `
#include <common>

// 接收指定颜色
uniform vec3 iColor;

void main() {
  gl_FragColor = vec4(iColor, 0.50);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  iTime: { value: 0},
  iResolution: { value: new Vector3() },
  // 随机产生颜色
  iColor: { value: new Color(0xffffff * Math.random()) },
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms,
  // 支持透明度
  transparent: true,
})
scene.add(new Mesh(plane, material))


function resizeRendererToDisplaySize(renderer: WebGLRenderer) {
  const canvas = renderer.domElement
  const width = canvas.clientWidth
  const height = canvas.clientHeight
  const needResize = canvas.width !== width || canvas.height !== height

  if (needResize) {
    renderer.setSize(width, height, false)
  }

  return needResize
}

function render(time: number): void {
  time *= 0.001

  resizeRendererToDisplaySize(renderer)

  const canvas = renderer.domElement
  uniforms.iResolution.value.set(canvas.width, canvas.height, 1)
  uniforms.iTime.value = time

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)